#include "log.hpp"
#include "sharemem.hpp"


int main()
{
    //现在要为共享内存间的通信增加一个同步功能，采用管道的方式去实现
    int m = mkfifo("myfifo", 0666);
    if(m < 0)
    {
        log(Error,"创建管道文件失败:%s,errno:%d",strerror(errno),errno);
        exit(1);
    }
    //创建共享内存（创建方）
    int shmid = Creatshare();
    if(shmid<0){exit(2);}
    
    //挂起共享内存
    char* sc = (char*)shmat(shmid, nullptr, 0);//记得强转

    int fd = open("myfifo",O_RDONLY, 0666);
    //读取共享内存里的数据
    while(true)
    {
        cout << "processA receive: " << endl;
        char buffer[32];
        int n = read(fd, buffer, 1);//知道写入方发送通告（1），才进行下面的读取
        if(n == 0)//写入方关闭
        {
            cout << "close" << endl;
            struct shmid_ds ds;
            //写入前观察一次描述共享内存的结构体ds
            //shmctl(shmid, IPC_RMID, &ds); 
            shmctl(shmid, IPC_RMID, nullptr);//释放共享内存
            close(fd);
            unlink("myfifo");
            return 0;
        }
        cout << sc << endl;
    }
    return 0;
}